package ysq.xyg.host.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.host.dao.HostReportDao;
import ysq.xyg.host.model.po.HostDetail;
import ysq.xyg.host.model.po.HostReport;
import ysq.xyg.host.model.po.HostShop;
import ysq.xyg.host.model.vo.HostReportVo;
import ysq.xyg.host.model.vo.HostShopVo;
import ysq.xyg.host.service.HostDetailService;
import ysq.xyg.host.service.HostItemService;
import ysq.xyg.host.service.HostReportService;
import ysq.xyg.host.service.HostShopService;
import ysq.xyg.host.util.HostBaseContent;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.sys.service.SysConfigService;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.model.po.WebScoreRecord;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.web.service.WebScoreRecordService;
import ysq.xyg.web.util.WebBaseContent;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * 房产模块-报备service实现
 *
 * @author shengQiang yu
 * @date 2019-7-1 15:25:15
 */
@Service("hostReportService")
public class HostReportServiceImpl extends BaseServiceImpl<HostReport> implements HostReportService {

    @Resource
    private HostReportDao hostReportDao;
    @Resource
    private WebScoreRecordService webScoreRecordService;
    @Resource
    private HostDetailService hostDetailService;
    @Resource
    private HostShopService hostShopService;

    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private WebMemberService webMemberService;
    @Resource
    private HostItemService hostItemService;
    private HostReport hostReport;

    @Autowired
    public void setBaseDao(HostReportDao hostReportDao) {
        this.baseDao = hostReportDao;
    }


    /**
     * 分页查询
     *
     * @param hostReportVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    public ReturnEntity page(HostReportVo hostReportVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<HostReport> list = hostReportDao.listLeft(hostReportVo);
        // 需要查看是否是独立经纪人
        if (CollUtil.isNotEmpty(list)) {
            for (HostReport hostReport : list) {
                if (StringUtils.isNotEmpty(hostReport.getShopNumber())) {
                    HostShopVo hostShopVo = new HostShopVo();
                    hostShopVo.setNumber(hostReport.getShopNumber());
                    List<HostShop> hostShopList = hostShopService.acceptList(hostShopVo);
                    if (CollUtil.isEmpty(hostShopList)) {
                        continue;
                    }
                    hostReport.setShopName(hostShopList.get(0).getShopName());
                }
            }
        }
        PageInfo<HostReport> page=new PageInfo<HostReport>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }
    /**
     * 分页查询
     *
     * @param hostReportVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    public ReturnEntity pageMember(HostReportVo hostReportVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        // PageHelper.orderBy(" update_time desc");
        List<HostReport> list = hostReportDao.listLeftMember(hostReportVo);
        PageInfo<HostReport> page=new PageInfo<HostReport>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }
    /**
     * 修改状态
     *
     * @param hostReportVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    @Transactional
    public ReturnEntity update(HostReportVo hostReportVo, SysUser currentUser){
        hostReport=selectByPrimaryKey(hostReportVo.getId());
        if(ObjectUtil.isNull(hostReport)){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        hostReport.setUpdateTime(new Date());
        hostReport.setUpdateUser(currentUser.getId());
        // 1、报备成功，2、客户到访，3、认筹成功，4、无效客户
        if (HostBaseContent.HOST_REPORT_STATE_RCQR.equals(hostReportVo.getReportState())) {
            hostReport.setAllMoney(hostReportVo.getAllMoney());
            hostReport.setFeeMoney(hostReportVo.getFeeMoney());
        }
        hostReport.setReportState(hostReportVo.getReportState());
        int num = updateByPrimaryKey(hostReport);
        if (num <= 0) {
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        } else {
            if(HostBaseContent.HOST_REPORT_STATE_RCQR.equals(hostReport.getReportState()) && hostReport.getFeeMoney()>0){
                // HostItem hostItem = hostItemService.selectByPrimaryKey(hostReport.getItemId());
                WebMember member=webMemberService.selectByPrimaryKey(hostReport.getMemberId());
                // 当前会员添加金额
                HostDetail hostDetail=new HostDetail(currentUser);
                hostDetail.setShareMoney(hostReport.getFeeMoney());
                hostDetail.setReportId(hostReport.getId());
                hostDetail.setMemberId(member.getId());
                hostDetail.setDescripts("您推广楼盘成功，获取推广佣金");
                hostDetailService.insert(hostDetail);
                int score=new Double(hostReport.getFeeMoney()).intValue();
                WebScoreRecord webScoreRecord=new WebScoreRecord(currentUser);
                webScoreRecord.setExtraId(hostReport.getId());
                webScoreRecord.setScore(score);
                webScoreRecord.setMemberId(member.getId());
                webScoreRecord.setRecordType(WebBaseContent.WEB_RECORD_TYPE_TGSR);
                webScoreRecord.setDescripts("您推广楼盘成功，获取"+score+"个积分");
                webScoreRecordService.insert(webScoreRecord);

                member.setScore(member.getScore()+score);
                member.setShareNum(member.getShareNum()+hostReport.getFeeMoney());
                member.setMoney(member.getMoney()+hostReport.getFeeMoney());
                webMemberService.updateByPrimaryKey(member);

                // 关闭分销功能
                /*if(StrUtil.isNotEmpty(member.getOneCardNo())){
                    WebMember parentMember=webMemberService.selectEntityByCardNo(member.getOneCardNo());
                    if(parentMember!=null){
                        //获取配置的
                        List<SysConfig> sysConfigList=sysConfigService.acceptList(new SysConfigVo("share_money_config"));
                        if(sysConfigList!=null&&sysConfigList.size()>0){
                            SysConfig sysConfig=sysConfigList.get(0);
                            Double bfb=Double.parseDouble(sysConfig.getContent());
                            Double shareMoney=(hostDetail.getShareMoney()*bfb)/100;
                            //结单
                            HostDetail parentDetail=new HostDetail(currentUser);
                            parentDetail.setShareMoney(shareMoney);
                            parentDetail.setReportId(hostReport.getId());
                            parentDetail.setMemberId(parentMember.getId());
                            parentDetail.setDescripts("下级会员【"+BaseUtil.decodeBase64(member.getNickName())+"】推广楼盘成功，获取分销佣金。");
                            hostDetailService.insert(parentDetail);
                            int parentScore=new Double(shareMoney).intValue();

                            WebScoreRecord webScoreRecordParent=new WebScoreRecord(currentUser);
                            webScoreRecordParent.setExtraId(hostReport.getId());
                            webScoreRecordParent.setScore(parentScore);
                            webScoreRecordParent.setMemberId(parentMember.getId());
                            webScoreRecordParent.setRecordType(WebBaseContent.WEB_RECORD_TYPE_TGSR);
                            webScoreRecordParent.setDescripts("下级会员【"+BaseUtil.decodeBase64(member.getNickName())+"】推广楼盘成功，获取"+score+"个积分");
                            webScoreRecordService.insert(webScoreRecordParent);

                            parentMember.setScore(parentMember.getScore()+parentScore);
                            parentMember.setShareNum(parentMember.getShareNum()+shareMoney);
                            parentMember.setMoney(parentMember.getMoney()+shareMoney);
                            webMemberService.updateByPrimaryKey(parentMember);
                        }

                    }
                }*/

            }
        }
        return new ReturnEntity();
    }
    /**
     * 修改
     *
     * @param hostReportVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    @Transactional
    public ReturnEntity addOrUpdate(HostReportVo hostReportVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(hostReportVo.getId())){
            hostReport=new HostReport(currentUser);
            isUpate=false;
        }else{
            hostReport=selectByPrimaryKey(hostReportVo.getId());
            if(ObjectUtil.isNull(hostReport)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            hostReport.setUpdateTime(new Date());
            hostReport.setUpdateUser(currentUser.getId());
        }
        hostReport.setItemId(hostReportVo.getItemId());
        hostReport.setMemberId(hostReportVo.getMemberId());
        hostReport.setCustomerSource(hostReportVo.getCustomerSource());
        hostReport.setName(hostReportVo.getName());
        hostReport.setSex(hostReportVo.getSex());
        hostReport.setPhone(hostReportVo.getPhone());
        hostReport.setUseTime(hostReportVo.getUseTime());
        hostReport.setReportState(hostReportVo.getReportState());
        hostReport.setRemarks(hostReportVo.getRemarks());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(hostReport);
        }else{
            num=insert(hostReport);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }
    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    public ReturnEntity delete(String id, SysUser currentUser) {
        HostReport hostReport=selectByPrimaryKey(id);
        if(hostReport!=null){
            hostReport.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            hostReport.setUpdateTime(new Date());
            hostReport.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(hostReport);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param hostReportVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author shengQiang yu
     * @date 2019-7-1 15:25:15
     */
    public List<HostReport> acceptList(HostReportVo hostReportVo){
        Example example = new Example(HostReport.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(hostReportVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",hostReportVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return hostReportDao.selectByExample(example);
    }
    public List<HostReport> listLeft(HostReportVo hostReportVo){
        return hostReportDao.listLeft(hostReportVo);
    }

    @Override
    public int selectCountByItemId(String itemId) {
        return hostReportDao.selectCountByItemId(itemId);
    }

    @Override
    public int selectCountByStatus(String memberId, String reportState) {
        return hostReportDao.selectCountByStatus(memberId, reportState);
    }

    @Override
    public boolean checkReportState(String phone) {
        Example example = new Example(HostReport.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", BaseConstant.BASE_REMOVE_TAG_NORMAL);
        criteria.andEqualTo("phone", phone);
        criteria.andNotEqualTo("reportState", BaseConstant.HOST_REPORT_STATE_FOUR);
        List<HostReport> hostReports = hostReportDao.selectByExample(example);
        if (CollUtil.isEmpty(hostReports)) {
            return true;
        }
        return false;
    }
}
